﻿using System;
using System.IO;
using WeifenLuo.WinFormsUI.Docking;
using System.Windows.Forms;
using System.Xml;
using System.Threading;
using Spider.Lib;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Models;
using Services;
using System.Linq;

namespace Spider.Forms
{
    public partial class CreateStaticHtml : DockContent
    {

        ContentsServices contentServs = new ContentsServices();
        TagServices tagServs = new TagServices();
        CategoryServices categoryServs = new CategoryServices();
        RelevanceServices relevServs = new RelevanceServices();
        public CreateStaticHtml()
        {
            InitializeComponent();
        }

        Thread thread1 = null;
        private void btnStart_Click(object sender, EventArgs e)
        {
            thread1 = new Thread(btnDo_Work);
            thread1.Start();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                if (thread1 != null)
                    thread1.Abort();
            }
            catch (Exception ex)
            {
                // log
                LogHelper.Error(ex);
            }
            finally
            {
                StringFactory.ThreadState = "Stop";
                btnStart.Enabled = true;
                btnStop.Enabled = false;
            }
        }
        void btnDo_Work(object obj)
        {
            if (StringFactory.ThreadState == "Start")
                return;
            StringFactory.ThreadState = "Start";

            string framePath = StringFactory.WebSiteDir + "\\Admins\\Templates\\frame.html";
            string viewHtml = IOHelper.Read(framePath);

            if (rbtnSinge.Checked)
            {
                int t = 0;
                if (!int.TryParse(numSinge.Value.ToString(), out t))
                {
                    UpdateName("不是整数类型");
                    StringFactory.ThreadState = "Stop";
                    return;
                }
                Contents _contentsAdd = contentServs.GetBySeed(t);
                if (_contentsAdd != null)
                    UpdateName(_contentsAdd.Name);
                else return;


                string contents = IOHelper.Read(StringFactory.WebSiteDir + "\\_upload\\contents\\" + _contentsAdd.Seed / 1000 + "\\" + _contentsAdd.Seed + ".txt");

                CreateHtml(_contentsAdd, contents, viewHtml);
            }

            if (rbtnSeris.Checked)
            {
                int start = 0;
                int end = 0;
                if (!int.TryParse(numStart.Value.ToString(), out start) & !int.TryParse(numEnd.Value.ToString(), out end))
                {
                    UpdateName("不是整数类型");
                    StringFactory.ThreadState = "Stop";
                    return;
                }

                for (int i = start; i <= end; i++)
                {
                    Contents _contentsAdd = contentServs.GetBySeed(i);
                    if (_contentsAdd != null)
                    {
                        UpdateName(_contentsAdd.Name);
                        string contents = IOHelper.Read(StringFactory.WebSiteDir + "\\_upload\\contents\\" + _contentsAdd.Seed / 1000 + "\\" + _contentsAdd.Seed + ".txt");
                        CreateHtml(_contentsAdd, contents, viewHtml);
                    }

                }
            }

            StringFactory.ThreadState = "Stop";
            UpdateProgress(100);
            UpdateName("结束!!");

            if (btnStart.InvokeRequired)
            {
                Action<bool> actionDeletegate = (x) =>
                {
                    btnStop.Enabled = false;
                    btnStart.Enabled = true;
                };
                btnStart.Invoke(actionDeletegate, false);
            }
        }


        private void UpdateName(object str)
        {
            if (lblName.InvokeRequired)
            {
                Action<string> actionDelegate = (x) =>
                {
                    this.lblName.Text = x.ToString();
                };
                lblName.Invoke(actionDelegate, str);

            }
            else
            {
                lblName.Text = str.ToString();
            }
        }
        private void UpdateProgress(int str)
        {
            //if (progressBar1.InvokeRequired)
            //{
            //    Action<int> actionDelegate = (x) =>
            //    {
            //        this.progressBar1.Value = str;
            //    };
            //    progressBar1.Invoke(actionDelegate, str);
            //}
            //else
            //{
            //    progressBar1.Value = str;
            //}
        }

        public void CreateHtml(Contents _contentsAdd, string contents, string viewHtml)
        {
            #region 生成静态页
            viewHtml = viewHtml.Replace("{$contents$}", contents);
            viewHtml = viewHtml.Replace("{$name$}", _contentsAdd.Name);
            viewHtml = viewHtml.Replace("{$state$}", _contentsAdd.State);
            viewHtml = viewHtml.Replace("{$updatetime$}", _contentsAdd.UpdateTime.ToShortDateString());
            viewHtml = viewHtml.Replace("{$seed$}", _contentsAdd.Seed.ToString());
            viewHtml = viewHtml.Replace("{$seed_pre$}", (_contentsAdd.Seed/1000).ToString());
            viewHtml = viewHtml.Replace("{$imgurl$}", _contentsAdd.ImgUrl);
            viewHtml = viewHtml.Replace("{$intro$}", _contentsAdd.Intro);


            List<Relevance> releList = relevServs.GetList(t => t.FirstId == _contentsAdd.Id);

            //tag
            string tagName = string.Empty;
            string tagUrl = string.Empty;
            string tag = string.Empty;
            foreach (var rele in releList.Where(t => t.TableName == "contents_tag"))
            {
                Tag t = tagServs.GetByID(rele.SecondId);
                if (t != null)
                {
                    tagName += t.TagName + ",";
                    tagUrl += t.TagUrl + ",";
                    tag += "<a href='/tag/" + t.TagUrl + "/' rel='tag'>" + t.TagName + "</a>,";
                }
            }
            viewHtml = viewHtml.Replace("{$tagname$}", tagName.TrimEnd(','));
            viewHtml = viewHtml.Replace("{$tagurl$}", tagUrl.TrimEnd(','));
            viewHtml = viewHtml.Replace("{$tag$}", tag.TrimEnd(','));

            //Category
            string categoryName = string.Empty;
            string categoryUrl = string.Empty;
            string category = string.Empty;
            foreach (var rele in releList.Where(t => t.TableName == "contents_category"))
            {
                Category ct = categoryServs.GetByID(rele.SecondId);
                if (ct != null)
                {
                    categoryName += ct.CategoryName + ",";
                    categoryUrl += ct.CategoryUrl + ",";
                    category += "<a href='/category/" + ct.CategoryUrl + "/' rel='category'>" + ct.CategoryName + "</a>,";
                }
            }

            viewHtml = viewHtml.Replace("{$categoryname$}", categoryName.TrimEnd(','));
            viewHtml = viewHtml.Replace("{$categoryurl$}", categoryUrl.TrimEnd(','));
            viewHtml = viewHtml.Replace("{$category$}", category.TrimEnd(','));

            IOHelper.Write(viewHtml, StringFactory.WebSiteDir + "\\view\\" + _contentsAdd.Seed / 1000 + "\\" + _contentsAdd.Seed + ".html");

            #endregion
        }
    }
}
